package com.ruoyi.recycle.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.recycle.domain.OrderEvaluate;
import com.ruoyi.recycle.domain.RecycleCommodity;
import com.ruoyi.recycle.domain.RecycleOrder;
import com.ruoyi.recycle.dto.OrderEvaluateDTO;
import com.ruoyi.recycle.dto.RecycleOrderDTO;
import com.ruoyi.recycle.service.IOrderEvaluateService;
import com.ruoyi.recycle.service.IRecycleOrderService;
import com.ruoyi.recycle.vo.RecycleOrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 回收订单Controller
 *
 * @author ruoyi
 * @date 2022-05-22
 */
@RestController
@RequestMapping("/recycleOrder")
@Api(tags = "回收订单")
public class RecycleOrderController extends BaseController {
    @Autowired
    private IRecycleOrderService recycleOrderService;
    @Resource
    private IOrderEvaluateService orderEvaluateService;

    ///**
    //* 查询回收订单列表
    // */
    // @RequiresPermissions("recycle:recycleOrder:list")
    //@GetMapping("/list")
    //public TableDataInfo list(RecycleOrder recycleOrder) {
    // startPage();
    //List<RecycleOrder> list = recycleOrderService.selectRecycleOrderList(recycleOrder);
    //  return getDataTable(list);
    //}


    /**
     * 分页查询回收订单
     */
    @PostMapping("/recycleOrderPageQuery")
    @ApiOperation("分页查询回收订单")
    public IPage<RecycleOrderVO> recycleOrderPageQuery(@RequestBody RecycleOrderDTO queryDTO) throws Exception{
        return recycleOrderService.selectOrderPage(queryDTO);
    }
    /**
     * 分页查询回收订单
     */
    @PostMapping("/recycleOrderTotalMoney")
    @ApiOperation("查询回收订单总金额")
    public AjaxResult recycleOrderTotalMoney(@RequestBody RecycleOrderDTO queryDTO) throws Exception{
        return recycleOrderService.recycleOrderTotalMoney(queryDTO);
    }

    /**
     * 导出回收订单列表
     */
    @RequiresPermissions("recycle:recycleOrder:export")
    @Log(title = "回收订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出回收订单列表")
    @ApiIgnore
    public void export(HttpServletResponse response, RecycleOrder recycleOrder) {
        List<RecycleOrder> list = recycleOrderService.selectRecycleOrderList(recycleOrder);
        ExcelUtil<RecycleOrder> util = new ExcelUtil<RecycleOrder>(RecycleOrder.class);
        util.exportExcel(response, list, "回收订单数据");
    }

    /**
     * 获取回收订单详细信息
     */
    @RequiresPermissions("recycle:recycleOrder:query")
    @GetMapping(value = "/{recycleOrderNo}")
    @ApiOperation("获取回收订单详细信息")
    @ApiImplicitParam(name = "recycleOrderNo", value = "id", dataType = "Long")
    public AjaxResult getInfo(@PathVariable("recycleOrderNo") String recycleOrderNo) {
        return AjaxResult.success(recycleOrderService.selectRecycleOrderById(recycleOrderNo)).put("detail",recycleOrderService.selectRecycleOrderDetailById(recycleOrderNo));
    }

    /**
     * 新增回收订单
     */
    @RequiresPermissions("recycle:recycleOrder:add")
    @Log(title = "回收订单", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增回收订单")
    public AjaxResult add(@RequestBody RecycleOrder recycleOrder) {
        return toAjax(recycleOrderService.insertRecycleOrder(recycleOrder));
    }

    /**
     * 修改回收订单
     */
    @RequiresPermissions("recycle:recycleOrder:edit")
    @Log(title = "回收订单", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改回收订单")
    public AjaxResult edit(@RequestBody RecycleOrder recycleOrder) {
        return toAjax(recycleOrderService.updateRecycleOrder(recycleOrder));
    }

    /**
     * 删除回收订单
     */
    @RequiresPermissions("recycle:recycleOrder:remove")
    @Log(title = "回收订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{recycleOrderNos}")
    @ApiOperation("删除回收订单")
    @ApiImplicitParam(name = "recycleOrderNos", value = "回收订单订单号集合", dataType = "List")
    public AjaxResult remove(@PathVariable String[] recycleOrderNos) {
        return toAjax(recycleOrderService.deleteRecycleOrderByIds(recycleOrderNos));
    }

    /**
     * 回收/家政 订单评价表
     */
    @PostMapping("/recycleOrderEvaluatePageQuery")
    @ApiOperation("分页查询回收/家政 订单评价表")
    public IPage<OrderEvaluate> recycleOrderEvaluatePageQuery(@RequestBody OrderEvaluateDTO queryDTO) {
        final OrderEvaluate orderEvaluate = new OrderEvaluate();
        BeanUtils.copyProperties(queryDTO, orderEvaluate);
        final LambdaQueryWrapper<OrderEvaluate> wrapper = Wrappers.lambdaQuery(orderEvaluate);
        if (queryDTO.getSearchTimeBegin() != null) {
            wrapper.ge(OrderEvaluate::getCreatedTime, queryDTO.getSearchTimeBegin());
        }
        if (queryDTO.getSearchTimeEnd() != null) {
            wrapper.le(OrderEvaluate::getCreatedTime, queryDTO.getSearchTimeEnd());
        }
        return orderEvaluateService.page(new Page<OrderEvaluate>()
                .setCurrent(queryDTO.getCurrentPage())
                .setSize(queryDTO.getPageSize()), wrapper);
    }

    /**
     * 回收/家政 订单评价表
     */
    @PostMapping("/saveOrderEvaluate")
    @ApiOperation("新增回收/家政 订单评价")
    public AjaxResult recycleEvaluateOrderPageQuery(@RequestBody OrderEvaluate orderEvaluate) {

        orderEvaluate.setCreatedTime(new Date());
        orderEvaluateService.save(orderEvaluate);
        return AjaxResult.success();
    }

    /**
     * 回收/家政 订单评价表
     */
    @GetMapping(value = "/evaluate/{recycleOrderNos}")
    @ApiOperation("获取回收/家政 订单评价")
    @ApiImplicitParam(name = "recycleOrderNos", value = "recycleOrderNos", dataType = "Long")
    public AjaxResult getRecycleOrderNos(@PathVariable("recycleOrderNos") Integer recycleOrderNos) {
        return AjaxResult.success(orderEvaluateService.getOne(new LambdaQueryWrapper<OrderEvaluate>().eq(OrderEvaluate::getOrderId,recycleOrderNos)));
    }

    /**
     * 输入回收订单重量
     */
    @Log(title = "回收订单", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/editRecycleOrder")
    @ApiOperation("输入回收订单重量")
    public R<Boolean> editRecycleOrder(@RequestBody List<RecycleCommodity> recycleCommodityList) {
        try {
            recycleOrderService.updateRecycleCommodityList(recycleCommodityList);
            return R.ok(true, "设置重量成功");
        } catch (Exception e) {
            return R.fail(false, "设置重量失败");
        }

    }

    /**
     * 实时计算回收订单可获得积分（快递订单专用）
     */
    @PostMapping(value = "/calculateRecycleOrderIntegral")
    @ApiOperation("实时计算回收订单可获得积分（快递订单专用）")
    public AjaxResult calculateRecycleOrderIntegral(@RequestBody List<RecycleCommodity> recycleCommodityList) {
        try {
            return recycleOrderService.culateRecycleOrderIntegral(recycleCommodityList);
        } catch (Exception e) {
            logger.error("异常{}",e.getMessage(),e);
          return AjaxResult.error("服务器异常，请联系管理员");
        }

    }


    /**
     * 回收订单确认收货接口
     */
    @Log(title = "回收订单确认收货接口", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/confirmReceipt/{orderId}")
    @ApiOperation("回收订单确认收货接口")
    public AjaxResult confirmReceipt(@PathVariable("orderId")String orderId) {
        try {
            return recycleOrderService.confirmReceipt(orderId);
        } catch (Exception e) {
            logger.error("异常信息{}",e.getMessage(),e);
            return AjaxResult.error("确认收货失败，系统异常，请联系管理员");
        }

    }




}
